﻿using LogLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using USBControlLib.Settings;

namespace USBControlLib
{
    public class UsbControl
    {
        private IntPtr WindowHandler = IntPtr.Zero;
        public string VersionInfo { private set; get; }
        public string Error { private set; get; }

        private List<Func<int>> listUSBControlFunc= new List<Func<int>>();

        private List<Func<int>> listQueryControlFunc = new List<Func<int>>();

        /// <summary>
        /// 指示通断板是否连接成功
        /// </summary>
        public bool Connected { private set; get; } = false;

        /// <summary>
        /// 当前执行的功能函数名称
        /// </summary>
        public string CurrentFunction { get; private set; }

        private USBControlSetting _controlSetting = null;
        private USBConnectSetting _connectSetting = null;
        public UsbControl(IntPtr wndHandler)
        {
            WindowHandler = wndHandler;
            InitFuncList();
        }

        private void InitFuncList()
        {
            listUSBControlFunc.Clear();
            listUSBControlFunc.Add(ControlLib.BoardControlChannel1);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel2);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel3);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel4);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel5);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel6);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel7);
            listUSBControlFunc.Add(ControlLib.BoardControlChannel8);

            listQueryControlFunc.Clear();
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel1);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel2);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel3);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel4);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel5);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel6);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel7);
            listQueryControlFunc.Add(ControlLib.BoardQueryChannel8);
        }

        public bool Init()
        {
            Error = "";
            ConfigService config = ConfigService.Get();
            _controlSetting = config.Batch;
            _connectSetting = config.BoardConfig;
            byte[] buffer = new byte[12];
            StringBuilder builder= new StringBuilder();
            int len = 24;
            string verInfo = "";
            //int code = ControlLib.BoardGetDllVersionControl(ref buffer[0], ref len);
            int code = ControlLib.BoardGetDllVersionControl(builder, ref len);
            int tailLen = builder.Length - len;
            builder.Remove(len, tailLen);
            if (code == 0)
            {
                VersionInfo = builder.ToString();
                Log.WriteAsync($"通断控制板程序版本号为:{VersionInfo}.");
            }
            else
            {
                Error = $"获取版本号失败，code={code}.";
                Log.WriteAsync(Error);
                return false;
            }
            code = ControlLib.BoardInitialCtrlDll(WindowHandler, 0, "");
            if (code != 0)
            {
                Error = $"控制板初始化失败，code:{code}";
                Log.WriteAsync(Error);
                return false;
            }         
            Log.WriteAsync("通断控制板初始化成功.");
            Connected = true;
            return true;
        }

        public bool Exit()
        {
            Error = "";
            int code = ControlLib.BoardUnInitialCtrlDll();
            if (code != 0)
            {
                Error = $"卸载动态库失败，code:{code}";
                Log.WriteAsync(Error);
                return false;
            }
            Connected = false;
            return true;
        }

        public async Task<bool> TakeAction(int actionCode, int channel)
        {
            Error = "";
            if(!Connected)
            {
                Error = "通断未连接，不能执行操作.";
                return false;
            }
            if (channel < 1 || channel > 8)
            {
                Error = $"USB通道设置错误:不存在的通道-{channel}";
                return false;
            }
            int code = 0;
            switch (actionCode)
            {
                case 1:
                    CurrentFunction = "BoardChannelConnect";
                    code = ControlLib.BoardChannelConnect(channel);
                    if (code == 0)
                    {
                        await _connectSetting.OnWaiting(channel, actionCode);
                        return true;
                    }
                    else
                    {
                        Error = $"执行BoardChannelDisConnect断开连接失败，错误代码{code}";
                        return false;
                    }
                case 2:
                    CurrentFunction = "BoardChannelDisConnect";
                    code = ControlLib.BoardChannelDisConnect(channel);
                    if (code == 0)
                    {
                        await _connectSetting.OnWaiting(channel, actionCode);
                        return true;
                    }
                   else
                    {
                        Error = $"执行BoardChannelDisConnect断开连接失败，错误代码{code}";
                        return false;
                    }
                case 3:
                    Func<int> funcControl = listUSBControlFunc[channel-1];
                    Func<int> funcQueryControl = listQueryControlFunc[channel-1];
                    CurrentFunction = funcControl.Method.Name;
                    code = funcControl();
                    if (code == 0)
                    {
                        CurrentFunction = funcQueryControl.Method.Name;
                        code = funcQueryControl();
                        if (code == 0)
                        {
                            await _connectSetting.OnWaiting(channel, actionCode);
                            return true;
                        }
                        else
                        {
                            Error = $"查询通断操作结果(BoardQueryChannel)失败，错误代码{code}";
                        }
                    }
                    else
                    {
                        Error = $"执行BoardControlChannel通断操作失败，错误代码{code}";
                    }
                    return false;
                default:
                    Error = $"功能代码错误:{actionCode}";
                    return false;
            }
        }

        public string GetActionName(int actionCode, int channel)
        {
            string action = "";
            switch (actionCode)
            {
                case 1:
                    action = $"对通道{channel}执行连通动作";
                    break;
                case 2:
                    action = $"对通道{channel}执行断开动作";
                    break;
                case 3:
                    action = $"对通道{channel}执行通断动作";
                    break;
                default:
                    action = $"对通道{channel}执行未知代号的操作";
                    break;
            }
            return action;
        }

    }
}
